package com.example.mybatislearning.again;

import com.example.mybatislearning.config.TestMapperProxy;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zhangfei
 * @date 2024/2/19 11:22
 **/
public class MyFactoryBean<T> implements FactoryBean<T> {
    private SqlSessionTemplate sqlSessionTemplate;
    private final Class<T> interfaceType;
    public MyFactoryBean(Class<T> interfaceType) {
        this.interfaceType = interfaceType;
    }
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate){
        this.sqlSessionTemplate = sqlSessionTemplate;
    }
    @Override
    public T getObject() throws Exception {
        return (T) Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class[]{interfaceType}, new InvocationHandler(){
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (Object.class.equals(method.getDeclaringClass())) {
                    return method.invoke(this, args);
                } else {
                    return "hello world";
                }
            }
        });
    }
    @Override
    public Class<?> getObjectType() {
        return this.interfaceType;
    }
}
